// 列出所有商品渠道价格的脚本
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

// 获取命令行参数（可选的商品名称过滤）
const args = process.argv.slice(2);
const productNameFilter = args[0] || null;

async function listProductPrices() {
  try {
    console.log('查询商品价格信息...');
    
    // 1. 获取所有商品（或指定商品）
    const whereClause = productNameFilter 
      ? { status: true, name: { contains: productNameFilter } }
      : { status: true };
    
    const products = await prisma.product.findMany({
      where: whereClause,
      orderBy: { name: 'asc' }
    });
    
    if (products.length === 0) {
      console.log('没有找到符合条件的商品');
      return;
    }
    
    console.log(`找到 ${products.length} 个商品`);
    
    // 2. 获取所有渠道
    const channels = await prisma.channel.findMany({
      where: { status: true },
      orderBy: { name: 'asc' }
    });
    
    console.log(`找到 ${channels.length} 个渠道`);
    console.log('\n==================== 商品价格列表 ====================');
    
    // 设置列宽
    const productNameWidth = 16;
    const channelWidth = 12;
    
    // 3. 打印表头
    let header = '商品名称'.padEnd(productNameWidth);
    channels.forEach(channel => {
      header += `| ${channel.name.padEnd(channelWidth - 2)}`;
    });
    console.log(header);
    
    // 打印分隔线
    let separator = '-'.repeat(productNameWidth);
    channels.forEach(() => {
      separator += '+-' + '-'.repeat(channelWidth - 2);
    });
    console.log(separator);
    
    // 4. 遍历每个商品，获取并显示各渠道价格
    for (const product of products) {
      // 查找该商品的所有渠道价格
      const prices = await prisma.productPrice.findMany({
        where: { productId: product.id }
      });
      
      // 创建价格映射，方便查询
      const priceMap = {};
      prices.forEach(price => {
        priceMap[price.channelId] = price.price;
      });
      
      // 打印商品价格行
      let productName = product.name;
      if (productName.length > productNameWidth - 1) {
        productName = productName.substring(0, productNameWidth - 3) + '..';
      }
      let row = productName.padEnd(productNameWidth);
      
      channels.forEach(channel => {
        const price = priceMap[channel.id] !== undefined ? `${priceMap[channel.id]}元` : '未设置';
        row += `| ${price.padEnd(channelWidth - 2)}`;
      });
      console.log(row);
    }
    
    console.log(separator);
    console.log('==================== 价格列表结束 ====================\n');
  } catch (error) {
    console.error('查询商品价格出错:', error);
  } finally {
    await prisma.$disconnect();
  }
}

// 执行查询
listProductPrices(); 